import { CategoryService } from './../../service/category.service';
import { AbstractController, Restful, Group, Autowire } from 'ts-express-restful';
import { Request, Response, NextFunction } from 'express-serve-static-core';
import Category from '../../model/category.model';

@Group("admin")
@Restful()
export class CategoryController extends AbstractController { 
    @Autowire
    public categoryService!: CategoryService;
    $isValidId(id: string) { 
        return /^\d+$/.test(id);
    }

    async get(req: Request, res: Response, next: NextFunction) { 
        let { id } = req.params;
        const category = await this.categoryService.get(id);
        res.json(category);
    }
    
    async add(req: Request, res: Response, next: NextFunction) { 
        let { name, type } = req.body;
        const category = new Category();
        category.name = name;
        category.type = type;
        const newCategory = await this.categoryService.save(category);
        res.json(newCategory);
    }
    async update(req: Request, res: Response, next: NextFunction) { 
        let { name, type } = req.body;
        let { id } = req.params;
        const category = await this.categoryService.get(id);
        category.name = name;
        category.type = type;
        await category.save();
        res.json(category);
    }
    async find(req: Request, res: Response, next: NextFunction) { 
        let { page, pagesize } = req.query;
        const pager = await this.categoryService.find({}, page, pagesize);
        res.json(pager);
    }
}